package work.mediway.mdm.biz.service.patient.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.mediway.hos.common.utils.spring.SpringUtils;

import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import work.mediway.mdm.core.transport.ErrorMsgVO;
import work.mediway.mdm.biz.dto.dict.DictGeneralDTO;
import work.mediway.mdm.biz.dto.dict.DictGeneralDeleteDTO;
import work.mediway.mdm.biz.dto.patient.PatientQueryDTO;
import work.mediway.mdm.biz.dto.patient.PatientStorageDTO;
import work.mediway.mdm.biz.entity.patient.PaAddress;
import work.mediway.mdm.biz.entity.patient.PaIdentifier;
import work.mediway.mdm.biz.entity.patient.PaPatient;
import work.mediway.mdm.biz.entity.patient.RelPatient;
import work.mediway.mdm.biz.mapper.patient.RelPatientMapper;
import work.mediway.mdm.biz.service.common.CommonDictService;
import work.mediway.mdm.biz.service.patient.RelPatientService;
import work.mediway.mdm.biz.vo.patient.RelPatientVO;

@Slf4j
@Service
public class RelPatientServiceImpl extends ServiceImpl<RelPatientMapper, RelPatient> implements RelPatientService {

    @Override
    public ErrorMsgVO patientSave(PatientStorageDTO patientStorageDTO) {
        ErrorMsgVO msgVO = new ErrorMsgVO();
        List<PatientStorageDTO.RequestBean.DataBean> dataBeanList = patientStorageDTO.getRequest().getData();

        for (PatientStorageDTO.RequestBean.DataBean data : dataBeanList) {
            // 获取his ID
            String rePatHosPatientId = data.getREPAT_HosPatientID();
            if (StrUtil.isBlank(rePatHosPatientId)) {
                msgVO.setErrorMsg(data, "REPAT_HosPatientID 为空");
                break;
            } else {
                String idStr = IdUtil.getSnowflakeNextIdStr();
                data.setREPAT_PatientID(idStr);

                data.getPaPatient().setPAPAT_PatientID(idStr);
                data.getPA_Identifier().forEach(item -> item.setPAPATID_PatientID(idStr));
                data.getPA_Address().forEach(item -> item.setPAPATAD_PatientID(idStr));

                try {
                    // 主表
                    SpringUtil.getBean(CommonDictService.class).saveDictDetail(DictGeneralDTO.build(data, RelPatient.class), "");
                    // 患者信息
                    SpringUtil.getBean(CommonDictService.class).saveDictDetail(DictGeneralDTO.build(data, PaPatient.class), "");
                    // 证件
                    SpringUtil.getBean(CommonDictService.class).saveDictDetail(DictGeneralDTO.build(data.getPA_Identifier(), PaIdentifier.class), "");
                    // 地址
                    SpringUtil.getBean(CommonDictService.class).saveDictDetail(DictGeneralDTO.build(data.getPA_Address(), PaAddress.class), "");

                } catch (Exception e) {
                    msgVO.setErrorMsg(data, e.getMessage());
                    log.info("回滚数据======================");
                    Gson gson = new Gson();
                    String relPatientJsonStr = gson.toJson(data);
                    String paPatientJsonStr = gson.toJson(data.getPaPatient());
                    String paIdentifierJsonStr = gson.toJson(data.getPA_Identifier());
                    String paAddressJsonStr = gson.toJson(data.getPA_Address());

                    SpringUtils.getBean(CommonDictService.class).removeDict(new DictGeneralDeleteDTO(CollUtil.newArrayList(JSONUtil.toBean(relPatientJsonStr, new TypeReference<Map<String, Object>>() {
                        @Override
                        public Type getType() {
                            return super.getType();
                        }
                    }, true)), "Rel_Patient"));

                    SpringUtils.getBean(CommonDictService.class).removeDict(new DictGeneralDeleteDTO(CollUtil.newArrayList(JSONUtil.toBean(paPatientJsonStr, new TypeReference<Map<String, Object>>() {
                        @Override
                        public Type getType() {
                            return super.getType();
                        }
                    }, true)), "PA_Patient"));

                    SpringUtils.getBean(CommonDictService.class).removeDict(new DictGeneralDeleteDTO(JSONUtil.toBean(paIdentifierJsonStr, new TypeReference<List<Map<String, Object>>>() {
                        @Override
                        public Type getType() {
                            return super.getType();
                        }
                    }, true), "PA_Identifier"));
                    SpringUtils.getBean(CommonDictService.class).removeDict(new DictGeneralDeleteDTO(JSONUtil.toBean(paAddressJsonStr, new TypeReference<List<Map<String, Object>>>() {
                        @Override
                        public Type getType() {
                            return super.getType();
                        }
                    }, true), "PA_Address"));
                    e.printStackTrace();
                }
            }
        }
        msgVO.setCount(dataBeanList.size());
        return msgVO;
    }

    @Override
    public Page<RelPatientVO> patientList(PatientQueryDTO patientQueryDTO) {
        Page<RelPatientVO> page = new Page<>(patientQueryDTO.getCurrent(), patientQueryDTO.getSize());
        page.setRecords(this.baseMapper.patientList(page, patientQueryDTO));
        return page;
    }
}
